package com.flute.framework.filesystem;

import com.flute.framework.util.ftp.IFileOperation;

public class FileLock {

	private String name;
	private IFileOperation oper;
	public static final String LOCK = "filelock";

	public FileLock(String name, IFileOperation oper) {
		this.name = name;
		this.oper = oper;
		checkName();
	}

	private void checkName() {
		if (!name.endsWith(LOCK)) {
			name = name + "." + LOCK;
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
		checkName();
	}

	public boolean create(String folder) {
		boolean result = Boolean.TRUE;
		try {
			result &= oper.isDirectory(folder) || oper.mkdirs(folder);
			if (result) {
				result &= oper.isFile(oper.combin(folder, name))
						|| oper.createNewFile(folder, name);
			}
		} catch (Exception e) {
			result = Boolean.FALSE;
		}
		return result;
	}

	public boolean delete(String folder) {
		try {
			return  oper.delete(folder, name);
		} catch (Exception e) {
			return Boolean.FALSE;
		}
	}

	public boolean existed(String folder) {
		try {
			return oper.exists(oper.combin(folder, name));
		} catch (Exception e) {
			return Boolean.FALSE;
		}
	}

	public static boolean isLockFile(String file, IFileOperation oper) {
		try {
			return oper.isFile(file) && file.endsWith("." + LOCK);
		} catch (Exception e) {
			return Boolean.FALSE;
		}
	}

}
